package com.hzdp.zookeeper;

import java.util.List;
import java.util.concurrent.CountDownLatch;

import org.apache.zookeeper.AsyncCallback;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.EventType;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;

public class ZookeeperDemo implements Watcher {

	private static CountDownLatch latch = new CountDownLatch(1);

	private static ZooKeeper zk;

	@Override
	public void process(WatchedEvent event) {
		if (KeeperState.SyncConnected == event.getState()) {
			if (EventType.None == event.getType() && null == event.getPath()) {
				latch.countDown();
			} else if (event.getType() == EventType.NodeChildrenChanged) {
				try {
					System.out.println("Reget Child:" + zk.getChildren(event.getPath(), true));
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

	public static void main(String[] args) throws Exception {
		zk = new ZooKeeper("127.0.0.1:2181", 5000, new ZookeeperDemo());
		System.out.println(zk.getState());

		try {
			latch.await();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println(zk.getState());

		String path1 = zk.create("/zk-demo-java", "hello world".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
		System.out.println("Create path1" + path1);
		String path2 = zk.create("/zk-demo-java2", "hello world".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
		System.out.println("Create path2" + path2);

		zk.create("/zk-demo-java3", "hello world".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL, new AsyncCallback.StringCallback() {

			@Override
			public void processResult(int rc, String path, Object ctx, String name) {
				System.out.println("in processResult rc=" + rc + ",path=" + path + ",ctx=" + ctx + ",name=" + name);
			}
		}, "I am context");
		zk.create("/zk-demo-java3", "hello world".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL, new AsyncCallback.StringCallback() {

			@Override
			public void processResult(int rc, String path, Object ctx, String name) {
				System.out.println("in processResult rc=" + rc + ",path=" + path + ",ctx=" + ctx + ",name=" + name);
			}
		}, "I am context");

		zk.create("/zk-demo-java/node1", "hello world ,node1".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
		List<String> children = zk.getChildren("/zk-demo-java", true);
		System.out.println("children" + children);
		zk.create("/zk-demo-java/node2", "hello world ,node1".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
		Thread.sleep(Integer.MAX_VALUE);

		byte[] data = zk.getData("/zk-demo-java/node2", true, null);
		System.out.println(new String(data));
	}

}
